<?php
session_start(); // 开始会话

if ($_SERVER["REQUEST_METHOD"] == "POST") {

    $username = $_POST["username"];
    $password = $_POST["password"];

    $servername = "localhost";
    $db_username = "陌上";
    $db_password = "123456";
    $dbname = "陌上";

    $conn = mysqli_connect($servername, $db_username, $db_password, $dbname);

    if (!$conn) {
        die("连接失败: " . mysqli_connect_error());
    }

    $sql = "SELECT * FROM users WHERE username = ?";
    $stmt = mysqli_prepare($conn, $sql);
    mysqli_stmt_bind_param($stmt, "s", $username);
    mysqli_stmt_execute($stmt);
    $result = mysqli_stmt_get_result($stmt);

    if ($row = mysqli_fetch_assoc($result)) {
        // 验证密码
        if (password_verify($password, $row['password'])) {
            $_SESSION['username'] = $username; // 设置会话变量
            header("Location: welcome.php");
            exit;
        } else {
            echo "用户名或密码错误，请重试。";
        }
    } else {
        echo "用户名或密码错误，请重试。";
    }

    mysqli_stmt_close($stmt);
    mysqli_close($conn);
}
?>
